<template>
  <view class="home-container">
    <!-- 顶部状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box" @tap="toSearch">
        <view class="search-icon">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
        </view>
        <text class="search-placeholder">搜索农药、化肥、种子...</text>
        <view class="search-btn">
          <uni-icons type="scan" size="18" color="#667eea"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 轮播图 -->
    <view class="banner-section" v-if="bannerList.length > 0">
      <swiper class="banner-swiper" indicator-dots="true" autoplay="true" interval="4000" duration="500">
        <swiper-item v-for="(item, index) in bannerList" :key="index">
          <view class="banner-item" @tap="toBannerDetail(item)">
            <image :src="item.image" mode="aspectFill" class="banner-image"></image>
            <view class="banner-overlay">
              <text class="banner-title">{{ item.title }}</text>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 快捷导航 -->
    <view class="quick-nav" v-if="categoryList.length > 0">
      <view class="nav-grid">
        <view 
          class="nav-item" 
          v-for="(item, index) in categoryList" 
          :key="index" 
          @tap="toCategory(item)"
        >
          <view class="nav-icon" :style="{ background: item.gradient || getDefaultGradient(index) }">
            <image :src="item.icon || getDefaultIcon(item.name)" mode="aspectFit" class="icon-image"></image>
          </view>
          <text class="nav-text">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 功能区块 -->
    <view class="feature-section">
      <view class="feature-grid">
        <view class="feature-card feature-primary" @tap="toSpecial">
          <view class="feature-content">
            <text class="feature-title">今日特价</text>
            <text class="feature-desc">精选优质农药</text>
            <text class="feature-price">低至6折</text>
          </view>
          <view class="feature-icon">
            <uni-icons type="fire" size="32" color="#FF6B6B"></uni-icons>
          </view>
        </view>
        
        <view class="feature-card feature-secondary" @tap="toCoupon">
          <view class="feature-content">
            <text class="feature-title">优惠券</text>
            <text class="feature-desc">新人专享</text>
            <text class="feature-price">满减50元</text>
          </view>
          <view class="feature-icon">
            <uni-icons type="gift" size="32" color="#4ECDC4"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品推荐 -->
    <view class="goods-section">
      <view class="section-header">
        <view class="header-left">
          <view class="section-icon">
            <uni-icons type="star-filled" size="20" color="#FFD93D"></uni-icons>
          </view>
          <text class="section-title">热门推荐</text>
        </view>
        <view class="header-right" @tap="toGoodsList">
          <text class="more-text">查看更多</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- 商品网格 -->
      <view class="goods-grid" v-if="goodsList.length > 0">
        <view 
          class="goods-card" 
          v-for="(item, index) in goodsList" 
          :key="index"
        >
          <!-- 商品主体 -->
          <view class="goods-main" @tap="toGoodsDetail(item)">
            <view class="goods-image-wrapper">
              <image 
                :src="item.specs[0].img_url" 
                mode="aspectFill" 
                class="goods-image"
                @load="onImageLoad"
                @error="onImageError"
                :lazy-load="true"
              ></image>
              <view v-if="item.originalPrice && item.originalPrice > item.specs[0].retail_price" class="discount-badge">
                <text class="discount-text">{{ Math.round((1 - item.specs[0].retail_price / item.originalPrice) * 100) }}%</text>
              </view>
              <!-- 收藏按钮 -->
              <!-- <view class="favorite-btn" @tap.stop="toggleFavorite(item, index)" :class="{ active: item.isFavorited }">
                <uni-icons :type="item.isFavorited ? 'heart-filled' : 'heart'" size="16" :color="item.isFavorited ? '#FF6B6B' : '#fff'"></uni-icons>
              </view> -->
              <!-- 图片加载占位符 -->
              <view class="image-placeholder" v-if="!item.specs[0].img_url">
                <view class="placeholder-icon">📷</view>
              </view>
            </view>
            <view class="goods-info">
              <text class="goods-name">{{ item.goods_name }}</text>
              <view class="goods-tags">
                <text class="tag_1">正品保证</text>
                <text class="tag_2" v-if="item.sales_quantity > 100">热销</text>
                <text class="tag_3" v-if="item.specs[0].retail_price < 50">优惠</text>
              </view>
              <view class="price-section">
                <view class="price-row">
                  <text class="current-price">¥{{ parseFloat(getDisplayPrice(item)).toFixed(2) }}</text>
                  <text v-if="item.originalPrice && item.originalPrice > getDisplayPrice(item)" class="original-price">¥{{ parseFloat(item.originalPrice || 0).toFixed(2) }}</text>
                </view>
                <!-- 价格详情行 -->
                <view class="price-detail-row" v-if="getCustomPrice(item) > 0 && getCustomPrice(item) !== getRetailPrice(item)">
                  <text class="retail-price">零售价: ¥{{ parseFloat(getRetailPrice(item)).toFixed(2) }}</text>
                  <text class="custom-price">会员价: ¥{{ parseFloat(getCustomPrice(item)).toFixed(2) }}</text>
                </view>
                <view class="info-row">
                  <text class="sales-text">已售{{ item.sales_quantity }}件</text>
                  <text class="stock-text" :class="{ 'low-stock': getTotalStock(item) <= 10 }">
                    库存{{ getTotalStock(item) }}件
                  </text>
                </view>
              </view>
            </view>
            
          </view>
          
          <!-- 购物车操作区域 --> <!-- 数量控制器（当商品已在购物车中时显示） -->
        
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-grid" v-if="goodsList.length === 0">
        <view class="loading-card" v-for="n in 6" :key="n">
          <view class="loading-image"></view>
          <view class="loading-content">
            <view class="loading-line long"></view>
            <view class="loading-line medium"></view>
            <view class="loading-line short"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加微信授权测试按钮 -->
    <!-- <view class="wechat-auth-section">
      <button 
        class="wechat-auth-btn" 
        @tap="goToWechatAuth"
        hover-class="wechat-auth-btn-hover"
      >
        <uni-icons type="weixin" size="20" color="#fff"></uni-icons>
        <text>微信授权测试</text>
      </button>
    </view>

    <view class="api-test-section">
      <button 
        class="api-test-btn" 
        @tap="goToApiTest"
        hover-class="api-test-btn-hover"
      >
        <uni-icons type="gear" size="20" color="#fff"></uni-icons>
        <text>API接口测试</text>
      </button>
    </view> -->

    <!-- 调试信息显示区域 -->
    <view class="debug-section" v-if="showDebug">
      <view class="debug-header">
        <text class="debug-title">调试信息</text>
        <button class="debug-close" @tap="showDebug = false">关闭</button>
      </view>
      <view class="debug-content">
        <view class="debug-item">
          <text class="debug-label">分类数量:</text>
          <text class="debug-value">{{ categoryList.length }}</text>
        </view>
        <view class="debug-item">
          <text class="debug-label">商品数量:</text>
          <text class="debug-value">{{ goodsList.length }}</text>
        </view>
        <view class="debug-item">
          <text class="debug-label">轮播图数量:</text>
          <text class="debug-value">{{ bannerList.length }}</text>
        </view>
        <view class="debug-item">
          <text class="debug-label">加载状态:</text>
          <text class="debug-value">{{ JSON.stringify(loading) }}</text>
        </view>
        <view class="debug-item" v-if="goodsList.length > 0">
          <text class="debug-label">商品示例:</text>
          <text class="debug-value">{{ JSON.stringify(goodsList[0], null, 2) }}</text>
        </view>
      </view>
    </view>

    <!-- 调试按钮 -->
    <view class="debug-btn-section">
      <button 
        class="debug-btn" 
        @tap="toggleDebug"
        size="mini"
      >
        {{ showDebug ? '隐藏调试' : '显示调试' }}
      </button>
    </view>

    <!-- 微信授权快速访问组件 -->
    <WechatAuthQuickAccess 
      :show="true" 
      position="bottom-right"
    />

    <!-- 底部占位 -->
    <view class="bottom-safe"></view>
  </view>
</template>

<script>
import { getGoodsList } from '@/api/goods'
import { getCategoryList } from '@/api/goods/category'
import { getBannerList } from '@/api/goods/banner'
import { clearStorageCache } from '@/utils/auth'
import WechatAuthQuickAccess from '@/components/wechat'

export default {
  components: {
    WechatAuthQuickAccess
  },
  data() {
    return {
      bannerList: [],
      categoryList: [],
      goodsList: [],
      loading: {
        banner: false,
        category: false,
        goods: false
      },
      // 购物车状态
      cartItems: [], // 存储购物车商品
      showDebug: false
    }
  },

  onLoad() {
    this.loadBannerList()
    this.loadCategoryList()
    this.loadGoodsList()
    this.loadCartFromStorage() // 加载购物车数据
  },

  onPullDownRefresh() {
    Promise.all([
      this.loadBannerList(),
      this.loadCategoryList(),
      this.loadGoodsList()
    ]).finally(() => {
      this.loadCartFromStorage() // 刷新时重新加载购物车
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    // 加载轮播图
    async loadBannerList() {
      if (this.loading.banner) return
      this.loading.banner = true
      
      try {
        const res = await getBannerList({ position: 'home' })
        
        if (res && (res.code === 200 || res.code === 0)) {
          this.bannerList = res.data || []
        } else {
          this.setDefaultBanners()
        }
      } catch (error) {
        this.setDefaultBanners()
      } finally {
        this.loading.banner = false
      }
    },

    // 加载分类列表
    async loadCategoryList() {
      if (this.loading.category) return
      this.loading.category = true
      try {
        const res = await getCategoryList({ page: 1, page_size: 20 })
        console.log('分类API响应:', res)
        
        if (res && (res.code === 200 || res.code === 0)) {
          let categories = []
          
          // 处理不同的数据结构
          if (res.data && res.data.list) {
            categories = res.data.list
          } else if (res.data && res.data.items) {
            categories = res.data.items
          } else if (res.data && Array.isArray(res.data)) {
            categories = res.data
          } else if (res.list) {
            categories = res.list
          } else if (res.items) {
            categories = res.items
          } else if (Array.isArray(res)) {
            categories = res
          }
          
          console.log('处理后的分类数据:', categories)
          
          // 过滤并映射数据
          this.categoryList = categories
            .filter(item => item && (item.class_id !== "0" && item.class_id !== 0))
            .slice(0, 8)
            .map(item => ({
              id: item.class_id || item.id,
              name: item.class_name || item.name,
              icon: item.icon || this.getDefaultIcon(item.class_name || item.name)
            }))
            
          console.log('最终分类列表:', this.categoryList)
        } else {  
          console.log('分类API返回错误，使用默认分类')
          this.setDefaultCategories()
        }
      } catch (error) {
        console.error('加载分类失败:', error)
        this.setDefaultCategories()
      } finally {
        this.loading.category = false
      }
    },

    // 设置默认轮播图
    setDefaultBanners() {
      this.bannerList = [
        {
          id: 1,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          title: '春季农药促销季'
        },
        {
          id: 2,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          title: '化肥优惠大放送'
        },
        {
          id: 3,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          title: '优质种子新品上市'
        }
      ]
    },

    // 设置默认分类
    setDefaultCategories() {
      this.categoryList = [
        { id: 1, name: '杀虫剂', icon: '/static/images/icon/meikaozixun.optimized.png' },
        { id: 2, name: '杀菌剂', icon: '/static/images/icon/yanzhaodashuju.optimized.png' },
        { id: 3, name: '除草剂', icon: '/static/images/icon/yuanxiaodashuju.optimized.png' },
        { id: 4, name: '化肥', icon: '/static/images/icon/yuanxiaopinggu.optimized.png' },
        { id: 5, name: '种子', icon: '/static/images/icon/yuanxiaotuixuanke.optimized.png' },
        { id: 6, name: '农具', icon: '/static/images/icon/zhengcejiedu.optimized.png' },
        { id: 7, name: '园艺', icon: '/static/images/icon/zhiyuanjiance.optimized.png' },
        { id: 8, name: '更多', icon: '/static/images/icon/zhiyeku_1.optimized.png' }
      ]
    },

    // 获取默认渐变色
    getDefaultGradient(index) {
      const gradients = [
        'linear-gradient(135deg, #FF6B6B, #FF8E8E)',
        'linear-gradient(135deg, #4ECDC4, #44C6B8)',
        'linear-gradient(135deg, #45B7D1, #3A9BC1)',
        'linear-gradient(135deg, #96CEB4, #85C1A6)',
        'linear-gradient(135deg, #FFEAA7, #FDCB6E)',
        'linear-gradient(135deg, #DDA0DD, #D1A3D1)',
        'linear-gradient(135deg, #FD79A8, #F470A8)',
        'linear-gradient(135deg, #B8B8B8, #A8A8A8)'
      ]
      return gradients[index % gradients.length]
    },

    // 获取默认图标
    getDefaultIcon(name) {
      const iconMap = {
        '杀虫剂': '/static/images/icon/meikaozixun.optimized.png',
        '杀菌剂': '/static/images/icon/yanzhaodashuju.optimized.png',
        '除草剂': '/static/images/icon/yuanxiaodashuju.optimized.png',
        '化肥': '/static/images/icon/yuanxiaopinggu.optimized.png',
        '种子': '/static/images/icon/yuanxiaotuixuanke.optimized.png',
        '农具': '/static/images/icon/zhengcejiedu.optimized.png',
        '园艺': '/static/images/icon/zhiyuanjiance.optimized.png'
      }
      return iconMap[name] || '/static/images/icon/zhiyeku_1.optimized.png'
    },

    async loadGoodsList() {
      try {
        console.log('开始加载商品列表...')
        const res = await getGoodsList({ page: 1, pageSize: 6, include_specs: true })
        console.log('商品API响应:', res)
        
        if (res && (res.code === 200 || res.code === 0 || res.success)) {
          let items = []
          
          // 处理不同的数据结构
          if (res.data && res.data.items) {
            items = res.data.items
          } else if (res.data && res.data.list) {
            items = res.data.list
          } else if (res.items) {
            items = res.items
          } else if (res.list) {
            items = res.list
          } else if (res.data && Array.isArray(res.data)) {
            items = res.data
          } else if (Array.isArray(res)) {
            items = res
          }
          
          console.log('处理后的商品数据:', items)
          
          // 获取零售价
          const getRetailPrice = (obj) =>
            obj.spec_price || obj.retail_price || obj.price || obj.retailPrice || obj.current_price || obj.currentPrice || obj.sale_price || obj.salePrice || obj.min_price || obj.minPrice || 0;
          
          // 获取自定义价格
          const getCustomPrice = (obj) =>
            obj.custom_price || obj.customPrice || obj.vip_price || obj.vipPrice || obj.member_price || obj.memberPrice || obj.special_price || obj.specialPrice || 0;
          
          // 获取原价
          const getOriginalPrice = (obj) =>
            obj.original_price || obj.originalPrice || obj.market_price || obj.marketPrice || obj.old_price || obj.oldPrice || getRetailPrice(obj);

          // 完整的字段映射，确保所有页面需要的字段都能正确获取
          this.goodsList = (items || []).map(item => {
            // 最大兼容的字段映射
            const getImage = (obj) =>
              obj.spec_image || obj.img_url || obj.image || obj.imgUrl || obj.imageUrl || obj.pic || obj.cover || obj.thumb || obj.thumbUrl || obj.main_image || obj.mainImage || '/static/images/default-goods.png';

            // 基础字段映射
            const mappedItem = {
              goods_id: item.goods_id || item.id || item.goodsId,
              goods_name: item.goods_name || item.name || item.title || item.goodsName || '商品名称',
              sales_quantity: item.sales_quantity || item.sales || item.salesQuantity || 0,
              originalPrice: getOriginalPrice(item),
              // 规格信息
              specs: []
            }
            
            // 处理规格信息
            if (item.specs && Array.isArray(item.specs) && item.specs.length > 0) {
              // 如果API返回了规格信息，进行字段映射
              mappedItem.specs = item.specs.map(spec => ({
                spec_id: spec.spec_id || spec.id || spec.specId || mappedItem.goods_id,
                img_url: getImage(spec) || getImage(item),
                retail_price: getRetailPrice(spec) || getRetailPrice(item),
                custom_price: getCustomPrice(spec) || getCustomPrice(item),
                original_price: getOriginalPrice(spec) || getOriginalPrice(item),
                stock: spec.spec_stock || spec.stock || spec.quantity || item.stock || 0,
                spec_name: spec.spec_name || spec.name || spec.specName || '默认规格'
              }))
              
              // 计算规格中的最低价格（优先显示自定义价格）
              const prices = mappedItem.specs.map(spec => {
                // 优先使用自定义价格，如果没有则使用零售价
                return spec.custom_price > 0 ? spec.custom_price : spec.retail_price
              }).filter(price => price > 0)
              
              if (prices.length > 0) {
                const minPrice = Math.min(...prices)
                // 将最低价格设置到第一个规格中，用于显示
                mappedItem.specs[0].display_price = minPrice
                mappedItem.originalPrice = minPrice
              }
            } else {
              // 如果没有规格信息，创建一个默认规格
              mappedItem.specs = [{
                spec_id: mappedItem.goods_id,
                img_url: getImage(item),
                retail_price: getRetailPrice(item),
                custom_price: getCustomPrice(item),
                original_price: getOriginalPrice(item),
                stock: item.spec_stock || item.stock || item.quantity || 0,
                spec_name: '默认规格'
              }]
            }
            
            // 确保价格字段正确
            if (!mappedItem.originalPrice) {
              mappedItem.originalPrice = mappedItem.specs[0].retail_price
            }
            
            return mappedItem
          })
          
          console.log('最终商品列表:', this.goodsList)
        } else {
          console.log('商品API返回错误，使用空列表')
          this.goodsList = []
        }
      } catch (error) {
        console.error('加载商品失败:', error)
        uni.showToast({
          title: '商品加载失败',
          icon: 'none',
          duration: 2000
        })
        this.goodsList = []
      }
    },

    toSearch() {
      uni.navigateTo({
        url: '/src/pages/search/index'
      })
    },

    toBannerDetail(item) {
    },

    toCategory(item) {
      uni.navigateTo({
        url: `/src/pages/goods/list?categoryId=${item.id}&categoryName=${item.name}`
      })
    },

    toSpecial() {
      uni.navigateTo({
        url: '/src/pages/goods/list?type=special'
      })
    },

    toCoupon() {
      uni.navigateTo({
        url: '/src/pages/coupon/center'
      })
    },

    toGoodsList() {
      uni.navigateTo({
        url: '/src/pages/goods/list'
      })
    },
    
    toGoodsDetail(item) {
      uni.navigateTo({
        url: `/src/pages/goods/detail?id=${item.goods_id}`
      })
    },
    
    onImageLoad() {
      // 图片加载成功
    },
    
    onImageError(e) {
      // 图片加载失败，可以设置默认图片
    },

    // 购物车相关方法
    
    // 获取商品在购物车中的数量
    getCartQuantity(item) {
      const cartItem = this.cartItems.find(cartItem => cartItem.id === item.goods_id)
      return cartItem ? cartItem.quantity : 0
    },

    // 添加商品到购物车
    addToCart(item) {
      const cartItem = {
        id: item.goods_id,
        goodsId: item.goods_id,
        name: item.goods_name,
        price: item.specs[0].retail_price,
        originalPrice: item.specs[0].original_price,
        image: item.specs[0].img_url,
        spec: item.specs[0].spec_name || '默认规格',
        quantity: 1,
        selected: true,
        freeShipping: true,
        authentic: true
      }

      this.cartItems.push(cartItem)
      
      // 添加成功反馈
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success',
        duration: 1500
      })

      // 添加触觉反馈
      uni.vibrateShort({
        type: 'light'
      })

      // 保存到本地存储
      this.saveCartToStorage()
    },

    // 增加商品数量
    increaseCartQuantity(item) {
      const cartItem = this.cartItems.find(cartItem => cartItem.id === item.goods_id)
      if (cartItem) {
        cartItem.quantity++
        this.saveCartToStorage()
        
        // 添加触觉反馈
        uni.vibrateShort({
          type: 'light'
        })
      }
    },

    // 减少商品数量
    decreaseCartQuantity(item) {
      const cartItemIndex = this.cartItems.findIndex(cartItem => cartItem.id === item.goods_id)
      if (cartItemIndex !== -1) {
        const cartItem = this.cartItems[cartItemIndex]
        if (cartItem.quantity > 1) {
          cartItem.quantity--
        } else {
          // 数量为1时，从购物车中移除
          this.cartItems.splice(cartItemIndex, 1)
          uni.showToast({
            title: '已从购物车移除',
            icon: 'none',
            duration: 1000
          })
        }
        this.saveCartToStorage()
        
        // 添加触觉反馈
        uni.vibrateShort({
          type: 'light'
        })
      }
    },

    // 切换收藏状态
    toggleFavorite(item, index) {
      this.goodsList[index].isFavorited = !this.goodsList[index].isFavorited
      
      uni.showToast({
        title: this.goodsList[index].isFavorited ? '已收藏' : '已取消收藏',
        icon: 'none',
        duration: 1000
      })

      // 添加触觉反馈
      uni.vibrateShort({
        type: 'light'
      })
    },

    // 保存购物车到本地存储
    saveCartToStorage() {
      try {
        uni.setStorageSync('cartItems', this.cartItems)
      } catch (error) {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    },

    // 从本地存储加载购物车
    loadCartFromStorage() {
      try {
        const cartItems = uni.getStorageSync('cartItems')
        if (cartItems && Array.isArray(cartItems)) {
          this.cartItems = cartItems
        }
      } catch (error) {
        this.cartItems = []
      }
    },

    // 跳转到微信授权测试页面
    goToWechatAuth() {
      uni.navigateTo({
        url: '/src/pages/wechat-test/index'
      })
    },

    // 跳转到API测试页面
    goToApiTest() {
      uni.navigateTo({
        url: '/src/pages/api-test/index'
      })
    },

    // 切换调试显示
    toggleDebug() {
      this.showDebug = !this.showDebug
    },

    // 获取商品总库存
    getTotalStock(item) {
      return item.specs.reduce((total, spec) => total + spec.stock, 0)
    },
    
    // 获取显示价格（优先自定义价格，其次零售价）
    getDisplayPrice(item) {
      if (item.specs && item.specs[0]) {
        const spec = item.specs[0]
        // 优先显示自定义价格，如果没有则显示零售价
        return spec.custom_price > 0 ? spec.custom_price : spec.retail_price
      }
      return 0
    },
    
    // 获取零售价
    getRetailPrice(item) {
      if (item.specs && item.specs[0]) {
        return item.specs[0].retail_price || 0
      }
      return 0
    },
    
    // 获取自定义价格
    getCustomPrice(item) {
      if (item.specs && item.specs[0]) {
        return item.specs[0].custom_price || 0
      }
      return 0
    }
  }
}
</script>

<style lang="scss">
.home-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #F8FAFC 0%, #EDF2F7 100%);
}

.status-bar {
  height: var(--status-bar-height);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 搜索区域 */
.search-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx 30rpx 40rpx;
  position: relative;
}

.search-section::after {
  content: '';
  position: absolute;
  bottom: -30rpx;
  left: 0;
  right: 0;
  height: 30rpx;
  background: #F8FAFC;
  border-radius: 30rpx 30rpx 0 0;
}

.search-box {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 50rpx;
  padding: 0 30rpx;
  height: 80rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.search-icon {
  margin-right: 20rpx;
}

.search-placeholder {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.search-btn {
  padding: 10rpx;
}

/* 轮播图 */
.banner-section {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}

.banner-swiper {
  height: 340rpx;
  border-radius: 24rpx;
  overflow: hidden;
}

.banner-item {
  position: relative;
  height: 100%;
  border-radius: 24rpx;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
  padding: 40rpx 30rpx 30rpx;
}

.banner-title {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

/* 快捷导航 */
.quick-nav {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}

.nav-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;
  background: #fff;
  padding: 40rpx 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.3s ease;
}

.nav-item:active {
  transform: scale(0.95);
}

.nav-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
}

.icon-image {
  width: 40rpx;
  height: 40rpx;
}

.nav-text {
  font-size: 24rpx;
  color: #2D3748;
  font-weight: 500;
}

/* 功能区块 */
.feature-section {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}

.feature-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.feature-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}

.feature-card:active {
  transform: scale(0.98);
}

.feature-primary {
  background: linear-gradient(135deg, #FFE5E5, #FFF0F0);
}

.feature-secondary {
  background: linear-gradient(135deg, #E5F9F6, #F0FCFA);
}

.feature-content {
  flex: 1;
}

.feature-title {
  font-size: 28rpx;
  color: #2D3748;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}

.feature-desc {
  font-size: 24rpx;
  color: #718096;
  margin-bottom: 4rpx;
  display: block;
}

.feature-price {
  font-size: 24rpx;
  color: #E53E3E;
  font-weight: bold;
  display: block;
}

.feature-icon {
  margin-left: 20rpx;
}

/* 商品推荐 */
.goods-section {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
  background: #fff;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.header-left {
  display: flex;
  align-items: center;
}

.section-icon {
  margin-right: 12rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #2D3748;
}

.header-right {
  display: flex;
  align-items: center;
}

.more-text {
  font-size: 26rpx;
  color: #718096;
  margin-right: 8rpx;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

/* iPad 和更大屏幕适配 */
@media screen and (min-width: 768px) {
  .goods-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 24rpx;
  }
}

@media screen and (min-width: 1024px) {
  .goods-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 28rpx;
  }
}

.goods-card {
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.goods-card:active {
  transform: translateY(-4rpx) scale(0.98);
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.12);
}

.goods-card:hover {
  box-shadow: 0 6rpx 25rpx rgba(0, 0, 0, 0.1);
}

/* 商品主体区域 */
.goods-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-image-wrapper {
  position: relative;
  width: 100%;
  height: 280rpx;
  overflow: hidden;
}

.goods-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s ease;
}

.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f7fafc, #edf2f7);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .placeholder-icon {
    font-size: 60rpx;
    opacity: 0.3;
  }
}

.discount-badge {
  position: absolute;
  top: 12rpx;
  right: 12rpx;
  background: linear-gradient(135deg, #FF6B6B, #FF5252);
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.4);
  backdrop-filter: blur(8rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.discount-text {
  color: #fff;
  font-size: 18rpx;
  font-weight: bold;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

/* 收藏按钮 */
.favorite-btn {
  position: absolute;
  top: 12rpx;
  left: 12rpx;
  width: 56rpx;
  height: 56rpx;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(8rpx);
  transition: all 0.3s ease;
  z-index: 2;
  
  &.active {
    background: rgba(255, 107, 107, 0.9);
    transform: scale(1.1);
  }
  
  &:active {
    transform: scale(0.9);
  }
}

.goods-info {
  padding: 24rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 26rpx;
  color: #2D3748;
  font-weight: 500;
  line-height: 1.4;
  margin-bottom: 12rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  min-height: 72rpx;
  transition: color 0.2s ease;
}

.goods-card:active .goods-name {
  color: #667eea;
}

.goods-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6rpx;
  margin-bottom: 16rpx;
}

.tag {
  background: linear-gradient(135deg, #E2E8F0, #EDF2F7);
  color: #4A5568;
  font-size: 20rpx;
  padding: 6rpx 10rpx;
  border-radius: 12rpx;
  font-weight: 500;
  border: 1rpx solid rgba(74, 85, 104, 0.1);
}
.tag_1 {
  background: linear-gradient(135deg, #0d6be6, #0d6be6);
  color: #fafffd;
  font-size: 20rpx;
  padding: 6rpx 10rpx;
  border-radius: 12rpx;
  font-weight: 500;
  border: 1rpx solid rgba(74, 85, 104, 0.1);
}
.tag_2 {
  background: linear-gradient(135deg, #2ee51a, #2ee51a);
  color: #f9f7f7;
  font-size: 20rpx;
  padding: 6rpx 10rpx;
  border-radius: 12rpx;
  font-weight: 500;
  border: 1rpx solid rgba(74, 85, 104, 0.1);
}

.tag_3 {
  background: linear-gradient(135deg, #FFD93D, #FFC107);
  color: #fff;
  font-size: 20rpx;
  padding: 6rpx 10rpx;
  border-radius: 12rpx;
  font-weight: 500;
  border: 1rpx solid rgba(255, 193, 7, 0.1);
}
.price-section {
  margin-top: auto;
}

.price-row {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  margin-bottom: 8rpx;
}

.current-price {
  font-size: 28rpx;
  color: #E53E3E;
  font-weight: bold;
}

.original-price {
  font-size: 22rpx;
  color: #A0AEC0;
  text-decoration: line-through;
}

.sales-text {
  font-size: 20rpx;
  color: #718096;
  background: rgba(113, 128, 150, 0.1);
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  display: inline-block;
}

.info-row {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  margin-top: 8rpx;
}

.price-detail-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin: 6rpx 0;
  font-size: 20rpx;
}

.retail-price {
  color: #718096;
  text-decoration: line-through;
}

.custom-price {
  color: #FF6B6B;
  font-weight: 600;
  background: rgba(255, 107, 107, 0.1);
  padding: 3rpx 6rpx;
  border-radius: 4rpx;
}

.stock-text {
  font-size: 20rpx;
  color: #718096;
  background: rgba(113, 128, 150, 0.1);
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  display: inline-block;

  &.low-stock {
    color: #E53E3E;
    font-weight: bold;
  }
}

/* 购物车操作区域 */
.cart-action {
  padding: 20rpx;
  border-top: 1rpx solid #F7FAFC;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 添加到购物车按钮 */
.add-cart-btn {
  width: 64rpx;
  height: 64rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:active {
    transform: scale(0.9);
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
  }
}

/* 数量控制器 */
.quantity-controls {
  display: flex;
  align-items: center;
  background: #F7FAFC;
  border-radius: 32rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.quantity-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  transition: all 0.2s ease;
  
  &:active {
    background: #F0F0F0;
    transform: scale(0.95);
  }
  
  &.decrease {
    border-radius: 32rpx 0 0 32rpx;
  }
  
  &.increase {
    border-radius: 0 32rpx 32rpx 0;
  }
}

.quantity-text {
  min-width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: 600;
  color: #667eea;
  background: #fff;
}

/* 加载动画 */
.loading-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.loading-card {
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.loading-image {
  width: 100%;
  height: 280rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

.loading-content {
  padding: 24rpx;
}

.loading-line {
  height: 24rpx;
  border-radius: 12rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  margin-bottom: 12rpx;
  
  &.long {
    width: 80%;
  }
  
  &.medium {
    width: 60%;
  }
  
  &.short {
    width: 40%;
  }
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.bottom-safe {
  height: env(safe-area-inset-bottom);
  height: constant(safe-area-inset-bottom);
}

.wechat-auth-section {
  padding: 30rpx;
  margin: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.wechat-auth-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #07c160, #06ad56);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 44rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(7, 193, 96, 0.3);
  transition: all 0.3s ease;
}

.wechat-auth-btn:active {
  transform: scale(0.98);
}

.wechat-auth-btn-hover {
  opacity: 0.8;
  transform: scale(0.98);
}

.wechat-auth-btn::after {
  border: none;
}

.api-test-section {
  padding: 30rpx;
  margin: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.api-test-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #07c160, #06ad56);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 44rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(7, 193, 96, 0.3);
  transition: all 0.3s ease;
}

.api-test-btn:active {
  transform: scale(0.98);
}

.api-test-btn-hover {
  opacity: 0.8;
  transform: scale(0.98);
}

.api-test-btn::after {
  border: none;
}

/* 调试区域样式 */
.debug-section {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-height: 60%;
  background: rgba(0, 0, 0, 0.9);
  border-radius: 20rpx;
  padding: 30rpx;
  z-index: 9999;
  backdrop-filter: blur(10rpx);
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
  padding-bottom: 15rpx;
}

.debug-title {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
}

.debug-close {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
}

.debug-content {
  max-height: 400rpx;
  overflow-y: auto;
}

.debug-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
  padding: 10rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10rpx;
}

.debug-label {
  color: #fff;
  font-size: 26rpx;
  font-weight: 500;
}

.debug-value {
  color: #4ECDC4;
  font-size: 26rpx;
  font-weight: bold;
}

.debug-btn-section {
  position: fixed;
  bottom: 120rpx;
  right: 30rpx;
  z-index: 9998;
}

.debug-btn {
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  border: none;
  padding: 15rpx 25rpx;
  border-radius: 25rpx;
  font-size: 24rpx;
  backdrop-filter: blur(10rpx);
}

/* 微信授权快速访问组件 */
.WechatAuthQuickAccess {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  max-height: 50%;
  z-index: 9997;
}
</style>